<template>
    <div>
        <el-input v-model="findInfo" placeholder="请输入想查询的攻略" style="width: 200px;margin: 10px 0;"></el-input><el-button
            style="margin:0 0 0 10px;" @click="findguide()">点击搜索</el-button>
        <el-table :data="guideList" style="width: 100%;">
            <el-table-column label="攻略标题" prop="guide_name">
            </el-table-column>
            <el-table-column label="攻略地点" prop="guide_place" show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="创建者名字" prop="guide_createname" show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="创建时间" prop="guide_createtime">
            </el-table-column>
            <el-table-column label="攻略内容" prop="guide_information" show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column align="right" width="150">
                <template slot-scope="scope">
                    <el-button v-if="scope.row.guide_createid === '65ebdc472a75000065002c13'" size="mini"
                        @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.row._id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination style="width:50%;margin: 20px auto 0;" background @size-change="handleSizeChange"
            @current-change="handleCurrentChange" :current-page="pageIndex" :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize" layout=" prev, pager, next, jumper,total, sizes" :total="total">
        </el-pagination>
        <el-dialog title="攻略修改" :visible.sync="dialogFormVisible" width="25%">
            <el-form :model="form" ref="ruleForm">
                <el-form-item label="标题" :label-width="formLabelWidth" prop="guide_name">
                    <el-input v-model="form.guide_name" autocomplete="off" placeholder="标题"></el-input>
                </el-form-item>
                <el-form-item label="景点" :label-width="formLabelWidth" prop="guide_place">
                    <el-input v-model="form.guide_place" autocomplete="off" placeholder="景点"></el-input>
                </el-form-item>
                <el-form-item label="攻略信息" :label-width="formLabelWidth" prop="guide_information">
                    <el-input type="textarea" v-model="form.guide_information" autocomplete="off" placeholder="攻略信息"
                        maxlength="1000" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="图片信息" :label-width="formLabelWidth">
                    <el-upload style="margin:10px 0px!important;" :action="uploadUrl" list-type="picture-card"
                        :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :headers="headerObj"
                        :on-success="handleSuccess" :file-list="fileList">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import { _throttle } from '@/utils/throttle.js'
import api from '@/api'
export default {
    // 生命周期钩子函数 一个页面或者项目的从生到死的过程会有这个函数进行检测
    mounted() {  // 表示页面元素挂载完毕
        //   console.log(1111,api);
        this.getGuide();
    },
    data() {
        return {
            pageIndex: 1,
            pageSize: 10,
            total: 10,
            guideList: [],
            updataimg: [],
            findInfo: '',
            dialogFormVisible: false,
            form: {
                _id: "",
                guide_name: "",
                guide_information: "",
                guide_place: "",
                guide_createname: "",
                guide_createtime: "",
                guide_img: []
            },
            headerObj: {
                file: '',
            },
            //1.配置要上传文件的路由
            uploadUrl: "http://localhost:4000/file/uploadImg",
            fileList: [],
            dialogImageUrl: '',
            dialogVisible: false,
            disabled: false,
            formLabelWidth: '80px'
        }
    },
    watch: {
        findInfo(newVal, oldVal) {
            if (oldVal !== '' && newVal === '') {
                this.getGuide();
            }
        }
    },
    methods: {
        handleSuccess(response, file, fileList) {
            this.updataimg.push(response.url)
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            // console.log(file, fileList, dialogImageUrl);
            this.dialogVisible = true;
        },
        handleRemove(file) {
            let index = this.updataimg.indexOf(file.response.url);
            if (index !== -1) {
                this.updataimg.splice(index, 1);
            }
            console.log(this.form);
        },
        // vue2中箭头函数反而少用 箭头函数的this指向采用的是就近原则 而vue中我们不想使用就近原则
        // vue2中特殊情况必须得用箭头函数 这个情况我们碰
        async gettime() {
            let now = new Date();
            // 获取年份  
            let year = now.getFullYear();
            // 获取月份（注意：月份是从0开始的，所以我们需要加1）  
            let month = now.getMonth() + 1;
            month = month < 10 ? '0' + month : month; // 如果月份小于10，前面补0  
            // 获取日期  
            let date = now.getDate();
            date = date < 10 ? '0' + date : date; // 如果日期小于10，前面补0  
            // 获取小时  
            let hours = now.getHours();
            hours = hours < 10 ? '0' + hours : hours; // 如果小时小于10，前面补0  
            // 获取分钟  
            let minutes = now.getMinutes();
            minutes = minutes < 10 ? '0' + minutes : minutes; // 如果分钟小于10，前面补0  
            // 获取秒数  
            let seconds = now.getSeconds();
            seconds = seconds < 10 ? '0' + seconds : seconds; // 如果秒数小于10，前面补0  
            // 格式化日期和时间  
            let formattedDate = `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
            this.form.guide_createtime = await formattedDate;
        },
        async getGuide() {
            this.guideList = []
            let res = await api.getGuide({ pageIndex: this.pageIndex, pageSize: this.pageSize })
            if (res?.code == 200) {
                this.guideList = res.data;
                this.total = res.total
            } else {
                this.guideList = []
            }
        },
        handleEdit(userInfo) {
            this.dialogFormVisible = true
            this.form = { ...userInfo }
        },
        async handleDelete(_id) {
            let res = await api.delGuide({ _id });
            if (res?.code == 200) {
                this.$message({
                    message: res.message,
                    type: 'success'
                });
                this.getGuide();
            } else {
                this.$message.error(res.message);
            }
        },
        async handleOk() {
            if (this.form.guide_img.length == 0) {
                this.$message.error('请上传图片');
            } else {
                this.dialogFormVisible = false;
                this.gettime();
                this.fileList = [];
                this.form.guide_img = this.updataimg
                setTimeout(async () => {
                    let res = await api.updateGuide({ ...this.form })
                    if (res?.code == 200) {
                        this.$message({
                            message: res.message,
                            type: 'success'
                        });
                        this.getGuide();
                    } else {
                        this.$message.error(res.message);
                    }
                }, 0);
            }
        },
        handleSizeChange(val) {
            this.pageSize = val;
            this.getGuide()
        },
        handleCurrentChange(val) {
            this.pageIndex = val;
            this.getGuide()
        },
        submitForm(formName) {
            this.fileList = [];
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.handleOk();
                } else {
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.fileList = [];
            this.$refs[formName].resetFields();
        },
        findguide() {
            this._throttle(this.findmethod(), 3000)
        },
        async findmethod() {
            if (this.findInfo === '') {
                this.getGuide()
            } else {
                let res = await api.getGuide({ pageIndex: this.pageIndex, pageSize: this.pageSize })
                this.guideList = []
                if (res?.code == 200) {
                    for (let i = 0; i < res.data.length; i++) {
                        if (this.findInfo === res.data[i].guide_createname || this.findInfo === res.data[i].guide_name || this.findInfo === res.data[i].guide_place) {
                            this.guideList.push(res.data[i])
                        }
                    }
                    this.total = res.total
                } else {
                    this.guideList = []
                }
            }
        }
    },
}
</script>

<style lang="scss" scoped></style>